using System;
using System.Collections.Generic;
using System.Text;

namespace RollManager.Library.Utils
{
    abstract class MethodRepeater
    {
        /// <summary>
        /// A delegate method that is repeated without any return value.
        /// </summary>
        public delegate void VoidDelegate();

        /// <summary>
        /// Tries to call methodToRepeat repeatedly.
        /// Throws last recieved exception when all attempts fail.
        /// </summary>
        /// <param name="methodToRepeat">The method to repeat.</param>
        /// <param name="reporter">The logging mechanism for retry attempts.</param>
        /// <param name="numTries">The number of tries.</param>
        public static void RepeatMethod( VoidDelegate methodToRepeat, ProgressReporter reporter, int numTries )
        {
            int count = 0;
            while( true )
            {
                try
                {
                    methodToRepeat();
                    break;
                }
                catch( Exception ex )
                {
                    count++;

                    if( count >= numTries )
                    {
                        throw;
                    }
                    else
                    {
                        reporter.AddFormat( "Retry number {0} failed:", count );
                        reporter.Add( ex );
                    }
                }
            }
        }
    }
}
